package no.group.gowther.rest;

import cn.hutool.core.io.FileUtil;
import no.group.gowther.rest.vo.param.FileListQueryParam;
import no.group.gowther.service.dto.*;
import no.group.gowther.service.dto.param.FileDeleteDTO;
import no.group.gowther.service.dto.param.FileQueryListDTO;
import no.group.gowther.rest.vo.FileVO;
import no.group.gowther.rest.vo.Result;
import no.group.gowther.service.FileManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ayatsuji
 * @date 2022-04-11 22:41
 * @since
 */
@Validated
@RestController
@RequestMapping("api/file")
public class FileRestController {
    @Autowired
    private FileManageService fileManageService;

    @PostMapping
    public Result<ListDTO<FileVO>> queryFileList(@Validated @RequestBody FileListQueryParam fileListQueryParam) {
        FileQueryListDTO queryDTO = new FileQueryListDTO(
                StringUtils.hasText(fileListQueryParam.getDirPath()) ? Paths.get(fileListQueryParam.getDirPath()) : null,
                fileListQueryParam.getType(), fileListQueryParam);
        ListDTO<FileDTO> fileDTOListDTO = fileManageService.listFile(queryDTO);
        List<FileVO> fileVOs = fileDTOListDTO.list().stream().map(FileVO::new).collect(Collectors.toList());
        return Result.success(new ListDTO<>(fileDTOListDTO.total(), fileVOs));
    }

    @DeleteMapping
    public Result<?> deleteFile(@RequestBody @NotEmpty List<String> filePaths) {
        FileDeleteDTO fileDeleteDTO = new FileDeleteDTO(filePaths.stream().map(Paths::get).collect(Collectors.toList()));
        fileManageService.deleteFile(fileDeleteDTO);
        return Result.success();
    }
}
